/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.network;

import java.io.*;
import java.net.*;
import com.cse.p2p.common.*;
import com.cse.p2p.database.ClientDatabase;
import com.cse.p2p.database.ServerDatabase;
import com.cse.p2p.hash.HashImplement;
import com.cse.p2p.localfile.LocalFile;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import java.lang.ExceptionInInitializerError;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author TuyetNgan
 */
public class ClientReceiveDataTask extends Thread {
	
	private InputStream is = null;
	private Socket socket = null;
	private int fileID;
	private int pieceID;
//        private String pieceHash;
//        private String filePath;
	private byte[] content;
	private String IPsender;
	private ConcurrentHashMap<Integer, ClientControlTask_Client> downloadThreads;
	
	public ClientReceiveDataTask( Socket s, ConcurrentHashMap<Integer, ClientControlTask_Client> list ) {
		this.socket = s;
		this.downloadThreads = list;
//            this.pieceID = id;
//            this.fileID = fid;
//            this.pieceHash = hash;
//            this.filePath = path;
	}
	
	public void newConnection() {
		
		try {
			is = socket.getInputStream();
		}
		catch ( IOException e ) {
		}
	}
	
	public void closeConnection() {
		try {
			socket.close();
		}
		catch ( IOException e ) {
		}
	}
	
	public byte[] getContent() {
		return content;
	}
	
	public String getIP() {
		return IPsender;
	}
	
	public int getFileID() {
		return fileID;
	}
	
	public int getPieceID() {
		return pieceID;
	}
	
	@Override
	public void run() {
		newConnection();
		System.out.println( "Client receiving ... " );
		/* receive file from server */
		try {
			fileID = is.read();
			pieceID = is.read();
			System.err.println( "Receive file id " + fileID + " piece id " + pieceID + " from " + socket.getRemoteSocketAddress());
			IPsender = this.socket.getRemoteSocketAddress().toString().substring( 1, this.socket.getRemoteSocketAddress().toString().lastIndexOf( ":" ) );
			byte[] mybytearray = new byte[ client.logic.ClientLogicImplement.choosePiecesSize() ];
			File file = new File( CommonSettings.DEFAULT_TEMP_FOLDER + File.separatorChar + fileID + File.separatorChar + pieceID ) ;
			BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( file) );
			int count = 0;
			int read = 0;
			while ( (read = is.read( mybytearray) ) > 0) {
				// must be count 1
				System.out.println( "Receive new package number " + count + " : " + read + " Bytes" );
				bos.write( mybytearray, 0, read);
				bos.flush();
			}
			bos.close();
			try {
				ClientDatabase.NewPiece( pieceID, fileID, HashImplement.getHashFile( file, null ) );
			}
			catch ( Exception ex ) {
				ex.printStackTrace();
			}
			
			System.out.println( "Client recieved file or piece" );
			this.downloadThreads.get( fileID ).completeGettingAPiece();
		}
		catch ( EOFException ex ) {
			ex.printStackTrace();
		}
		catch ( UnknownHostException i ) {
			i.printStackTrace();
		}
		catch ( IOException i ) {
			i.printStackTrace();
		}
		closeConnection();
	}
}
